//
//  CollectController.m
//  GC_OC
//
//  Created by CoderDCLiu on 2023/3/16.
//

#import "CollectController.h"
#import "CollectListCell.h"
#import "FKCategory.h"
#import "FKCollectFilterView.h"
#import "GCAVPlayer.h"

@interface CollectController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, weak) UILabel *titleLabel;
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) NSMutableArray *dataSource;
@property(nonatomic, strong) UIView *navigationBarView;
@property(nonatomic, strong) UIButton *editorButton;
@property (nonatomic, assign) NSInteger total;
@property (nonatomic, weak) UIButton *filterBtn;
@property (nonatomic, weak) UIButton *sortBtn;
@property (nonatomic, weak) FKCollectFilterView *filterView;
@property (nonatomic, strong) NSArray *categories;
@property (nonatomic, strong) NSMutableDictionary *param;
@property(nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSArray *editActions;

@end

@implementation CollectController

- (NSMutableDictionary *)param
{
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
        _param[@"page"] = @"0";
        _param[@"limit"] = @"20";
    }
    return _param;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = XHUIColorFromRGB(0xF6F7F9);
    
    [self loadMenuData];
    [self setupUIView];
}

- (void)setupUIView {
    self.total = 0;
    
    FKCollectFilterView *filterView = [[FKCollectFilterView alloc] initWithFrame:CGRectMake(0, fkStatusAndNaBarH, fkScreenW, fkScreenH - fkStatusAndNaBarH)];
    [self.view addSubview:filterView];
    self.filterView = filterView;
    @weakify(self)
    filterView.completeBlock = ^(FKCategory * category) {
        @strongify(self)
        self.param[@"media_class_id"] = category.id;
        [self.tableView.mj_header beginRefreshing];
        [self filterBtnClicked:self.filterBtn];
    };
    filterView.cancelBlock = ^{
        [self filterBtnClicked:self.filterBtn];
    };
    
    self.navigationBarView = [UIView new];
    self.navigationBarView.backgroundColor =AppMainColor;
    [self.view addSubview:self.navigationBarView];

    UILabel *naviTitle = [UILabel new];
    naviTitle.text = @"所有收藏";
//    naviTitle.textAlignment = NSTextAlignmentCenter;
    naviTitle.userInteractionEnabled = YES;
    naviTitle.textColor = [UIColor whiteColor];
    naviTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [self.navigationBarView addSubview:naviTitle];
    self.titleLabel = naviTitle;

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backAction)];
    [naviTitle addGestureRecognizer:tap];

    UIButton *backButton = [UIButton new];
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:backButton];
    
    UIButton *filterBtn = [UIButton fk_btnWithTarget:self action:@selector(filterBtnClicked:) font:nil normalTitle:nil normalTitleColor:nil selectedTitle:nil selectedTitleColor:nil normalImg:[UIImage imageNamed:@"icon_filter_normal"] selectedImg:[UIImage imageNamed:@"icon_filter"] bgImg:nil selectedBgImg:nil];
    [self.navigationBarView addSubview:filterBtn];
    self.filterBtn = filterBtn;
    
    UIButton *sortBtn = [UIButton fk_btnWithTarget:self action:@selector(sortBtnClicked) font:nil normalTitle:nil normalTitleColor:nil selectedTitle:nil selectedTitleColor:nil normalImg:[UIImage imageNamed:@"order_asc"] selectedImg:nil bgImg:nil selectedBgImg:nil];
    [self.navigationBarView addSubview:sortBtn];
    self.sortBtn = sortBtn;
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view insertSubview:tableView belowSubview:filterView];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorInset = UIEdgeInsetsMake(0, 32, 0, 0);
    tableView.tableHeaderView = [UIView new];
    tableView.tableFooterView = [UIView new];
    tableView.backgroundColor = UIColor.groupTableViewBackgroundColor;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    UITableViewRowAction *action0 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        @strongify(self)
        [self fk_alertWithTitle:@"确定要删除当前收藏吗" confirm:^{
            @strongify(self)
            [self delete:indexPath];
        }];
    }];
    self.editActions = @[action0];

    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.mj_header beginRefreshing];
    
    [self.navigationBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.offset(fkStatusAndNaBarH);
    }];
    [naviTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(100);
        make.left.equalTo(backButton.mas_right).offset(0);
        make.top.mas_equalTo(StatusBarHeight);
        make.height.mas_equalTo(40);
    }];
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(32);
        make.left.equalTo(self.navigationBarView).offset(12);
        make.top.mas_equalTo(StatusBarHeight + 4);
    }];
    [filterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(fk_adjustW(32));
        make.centerY.equalTo(backButton);
        make.right.equalTo(sortBtn.mas_left).offset(-8);
    }];
    [sortBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.centerY.equalTo(filterBtn);
        make.right.offset(-15);
    }];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.navigationBarView.mas_bottom);
    }];
}

#pragma mark - private
- (void)delete:(NSIndexPath *)indexPath
{
    // 取消收藏就是删除
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    FKCollect *collect = self.dataSource[indexPath.row];
    param[@"media_id"] = collect.media_id;
    UserModel *user = [FKCacheTool userInfo];
    param[@"user_id"] = user.userinfo.user_id;
    [FKHttpTool postWithSuffix:@"/api/collect/setCollect" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            [SVProgressHUD showSuccessWithStatus:@"取消收藏成功"];
            
            NSMutableArray *temp = [NSMutableArray arrayWithArray:self.dataSource];
            [temp removeObjectAtIndex:indexPath.row];
            self.dataSource = temp;
            
            [self.tableView beginUpdates];
//            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.row] withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [self.tableView endUpdates];
        }
    } failure:nil];
}

- (void)filterBtnClicked:(UIButton *)btn
{
//    [self.filterView updateShow];
    btn.selected = !btn.isSelected;
    [self.filterView setShow:btn.isSelected];
}

- (void)sortBtnClicked
{
    self.sortBtn.selected = !self.sortBtn.isSelected;
    if (self.sortBtn.isSelected) {
        self.param[@"order_status"] = @"2";
    } else {
        self.param[@"order_status"] = @"1";
    }
    [self.tableView.mj_header beginRefreshing];
}

//- (void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:YES animated:true];
//
//}
//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    [self.navigationController setNavigationBarHidden:YES animated:true];
//}

- (void)loadData {
    [self.tableView.mj_footer resetNoMoreData];
    self.page = 0;
    self.param[@"page"] = @(self.page);
    [FKHttpTool getWithSuffix:@"/api/collect/getCollect" param:self.param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            self.dataSource = [FKCollect mj_objectArrayWithKeyValuesArray:result.data[@"data"]];
            self.total = [result.data[@"count"] integerValue];
            self.titleLabel.text = self.total > 0 ? fkFORMAT(@"所有收藏(%zd)", self.total) : @"所有收藏";
            [self.tableView reloadData];
            if (self.dataSource.count > 0) self.page++;
        }
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData
{
    self.param[@"page"] = @(self.page);
    [FKHttpTool getWithSuffix:@"/api/collect/getCollect" param:self.param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            NSArray *newArray = [FKCollect mj_objectArrayWithKeyValuesArray:result.data[@"data"]];
            if (newArray.count > 0) {
                NSMutableArray *array = [NSMutableArray arrayWithArray:self.dataSource];
                [array addObjectsFromArray:newArray];
                self.dataSource = array;
                [self.tableView reloadData];
                self.page++;
                
                self.total = [result.data[@"count"] integerValue];
                self.titleLabel.text = self.total > 0 ? fkFORMAT(@"所有收藏(%zd)", self.total) : @"所有收藏";
            } else {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
    }];
}


#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return  fk_adjustW(64);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CollectListCell *cell = [CollectListCell cellWith:tableView];
    FKCollect *collect = self.dataSource[indexPath.row];
    cell.data = collect.media;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    FKCollect *collect = self.dataSource[indexPath.row];
    
    [SUPlayerManager manager].currentSongIndex = indexPath.row;
    NSMutableArray *array = [NSMutableArray array];
    for (FKCollect *temp in self.dataSource) {
        NSInteger index = [self.dataSource indexOfObject:temp];
        [array addObject:[temp.media mj_keyValues]];
        
        temp.media.selected = index == indexPath.row;
    }
    [self.tableView reloadData];
    [SUPlayerManager manager].songList = array;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.editActions;
}

- (void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 网络请求
- (void)loadMenuData
{
    [FKHttpTool getWithSuffix:@"/api/collect/getMediaClass" param:nil success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            self.categories = [FKCategory mj_objectArrayWithKeyValuesArray:result.data];
            self.filterView.datas = self.categories;
        }
    } failure:nil];
}


@end
